<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警示框 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false" show-icon></el-alert>
      <!-- 级联选择器 -->
      <el-row class="cascaderRow">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectCascaderData"
            :options="cateList"
            :props="cateListProps"
            clearable
            @change="cascaderChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs页签 -->
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加按钮 -->
          <el-button
            type="primary"
            :disabled="isBtnDisable"
            @click="addParamDialogVisible = true"
          >添加动态参数</el-button>
          <!-- 表格 -->
          <el-table :data="manyTableData" stripe border style="width: 100%">
            <!-- 扩展列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  type
                  @close="tagClose(scope.row, index)"
                >{{tag}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInputRef"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="180"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParamShow(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParamBtn(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <!-- 添加按钮 -->
          <el-button
            type="primary"
            :disabled="isBtnDisable"
            @click="addParamDialogVisible = true"
          >添加静态属性</el-button>
          <!-- 表格 -->
          <el-table :data="onlyTableData" stripe border style="width: 100%">
            <!-- 扩展列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  type
                  @close="tagClose(scope.row, index)"
                >{{tag}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInputRef"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称" width="180"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParamShow(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParamBtn(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加' + title"
      :visible.sync="addParamDialogVisible"
      width="50%"
      @close="addParamDialogClose"
    >
      <el-form
        :model="addParamForm"
        :rules="addParamFormRules"
        ref="addParamFormRef"
        label-width="100px"
      >
        <el-form-item :label="title" prop="attr_name">
          <el-input v-model="addParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addAttrconfirm">确 定</el-button>
        <el-button @click="addParamDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="'编辑' + title"
      :visible.sync="editParamDialogVisible"
      width="50%"
      @close="editParamDialogClose"
    >
      <el-form
        :model="editParamForm"
        :rules="editParamFormRules"
        ref="editParamFormRef"
        label-width="100px"
      >
        <el-form-item :label="title" prop="attr_name">
          <el-input v-model="editParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editAttrconfirm">确 定</el-button>
        <el-button @click="editParamDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as allGoodsFunc from '@/network/goods'
export default {
  name: 'Param',
  data() {
    return {
      cateList: [],
      cateListProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      selectCascaderData: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addParamDialogVisible: false,
      addParamForm: {
        attr_name: ''
      },
      addParamFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      editParamDialogVisible: false,
      editParamForm: {
        attr_id: '',
        attr_name: ''
      },
      editParamFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      }
    }
  },
  computed: {
    isBtnDisable() {
      return !(this.selectCascaderData.length === 3)
    },
    cateId() {
      if (this.selectCascaderData.length !== 3) {
        return false
      } else {
        return this.selectCascaderData[2]
      }
    },
    title() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  created() {
    this.getCascaderData()
  },
  methods: {
    // 获取级联选择器中的分类数据
    async getCascaderData() {
      const { data, meta } = await allGoodsFunc.allCateList()
      if (meta.status !== 200) {
        return this.$message.error(meta.msg)
      } else {
        this.cateList = data
      }
    },
    // 级联选择器改变时触发
    cascaderChange() {
      if (this.selectCascaderData.length !== 3) {
        this.selectCascaderData = []
        this.manyTableData = []
        this.onlyTableData = []
        return false
      }
      this.getManyOrOnlyData()
    },
    // tab标签点击时触发
    tabClick() {
      if (this.selectCascaderData.length === 3) {
        this.getManyOrOnlyData()
      } else {
        this.$message.error('请选择商品分类')
      }
    },
    // 获取动态静态数据
    async getManyOrOnlyData() {
      const { data, meta } = await allGoodsFunc.getAttributes(
        this.cateId,
        this.activeName
      )
      if (meta.status !== 200) {
        return this.$message.error(meta.msg)
      } else {
        for (const item of data) {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        }
        if (this.activeName === 'many') {
          this.manyTableData = data
          console.log(this.manyTableData)
        } else {
          this.onlyTableData = data
          console.log(this.onlyTableData)
        }
      }
    },
    // 监听添加对话框close事件
    addParamDialogClose() {
      this.$refs.addParamFormRef.resetFields()
    },
    // 点击添加对话框的确认按钮
    addAttrconfirm() {
      this.$refs.addParamFormRef.validate(async valid => {
        if (!valid) {
          return false
        } else {
          const { meta } = await allGoodsFunc.addParamOrAttr(
            this.cateId,
            this.addParamForm.attr_name,
            this.activeName
          )
          if (meta.status !== 201) {
            return this.$message.error(meta.msg)
          } else {
            this.$message.success(meta.msg)
            this.getManyOrOnlyData()
            this.addParamDialogVisible = false
          }
        }
      })
    },
    // 监听编辑对话框close事件
    editParamDialogClose() {
      this.$refs.editParamFormRef.resetFields()
    },
    // 点击编辑属性对话框确定按钮
    editAttrconfirm() {
      this.$refs.editParamFormRef.validate(async valid => {
        if (!valid) {
          return false
        } else {
          const { meta } = await allGoodsFunc.editConfirm(
            this.cateId,
            this.editParamForm.attr_id,
            this.editParamForm.attr_name,
            this.activeName
          )
          if (meta.status !== 200) {
            return this.$message.error(meta.msg)
          } else {
            this.$message.success(meta.msg)
            this.getManyOrOnlyData()
            this.editParamDialogVisible = false
          }
        }
      })
    },
    // 点击编辑按钮
    async editParamShow(attrId) {
      const { data, meta } = await allGoodsFunc.selectParamById(
        this.cateId,
        attrId,
        this.activeName
      )
      if (meta.status !== 200) {
        return this.$message.error(meta.msg)
      } else {
        this.editParamForm.attr_id = data.attr_id
        this.editParamForm.attr_name = data.attr_name
        this.editParamDialogVisible = true
      }
    },
    // 点击删除按钮
    async deleteParamBtn(attrId) {
      const res = await this.$confirm(
        '此操作将永久删除该属性, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (res === 'confirm') {
        console.log(this.cateId)
        const { meta } = await allGoodsFunc.deleteParam(this.cateId, attrId)
        if (meta.status !== 200) {
          return this.$message.error(meta.msg)
        } else {
          this.$message({
            type: 'success',
            message: meta.msg
          })
          this.getManyOrOnlyData()
        }
      } else {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
    },
    // 添加tag处，点击回车或者失去焦点时，触发该函数
    handleInputConfirm(row) {
      row.inputVisible = false
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        return false
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      this.addOrCloseTag(row)
    },
    // 点击按钮切换input输入框
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInputRef.$refs.input.focus()
      })
    },
    // 删除tag
    tagClose(row, index) {
      row.attr_vals.splice(index, 1)
      this.addOrCloseTag(row)
    },
    // 添加或删除tag
    async addOrCloseTag(row) {
      const { meta } = await allGoodsFunc.addTag(
        this.cateId,
        row.attr_id,
        row.attr_name,
        row.attr_sel,
        row.attr_vals.join(' ')
      )
      if (meta.status !== 200) {
        return this.$message.error(meta.msg)
      } else {
        this.$message.success(meta.msg)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cascaderRow {
  margin: 15px 0;
}
.el-tag {
  margin-right: 10px;
}
.input-new-tag {
  width: 200px;
}
</style>
